/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bitetorrent.trackerComm;

import bitetorrent.MyThread;
import bitetorrent.helper.Request;
import bitetorrent.helper.Response;
import bitetorrent.Torrent;
import bitetorrent.model.AddressPort;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Robert Gunawan
 */
public class TrackerHandler extends MyThread {

    public Torrent torrent;
    public boolean stop = false;
    int downloaded = 0;
    int inc = 1;
    int port = 10000;
    

    public Response response = null;

    public TrackerHandler(Torrent torrent) {
        this.torrent = torrent;
    }

    @Override
    public void run() {
        String request = null;
        String stringResponse = null;
        String stringInterval;
        int interval;

        // Started
        request = Request.makeGetRequest(torrent, "started", port, 0, downloaded);
        stringResponse = Request.sendGetRequest(torrent.announce, request);

        if (stringResponse == null || stringResponse.isEmpty()) {
            System.out.println("Koneksi gagal.");
            return;
        }

        while (loop) {
            if (stop) {
                loop = false;
                request = Request.makeGetRequest(torrent, "stopped", port, 0, downloaded);
                stringResponse = Request.sendGetRequest(torrent.announce, request);
            } else {
                request = Request.makeGetRequest(torrent, null, port, 0, downloaded += inc);
                stringResponse = Request.sendGetRequest(torrent.announce, request);
                if (stringResponse == null) {
                    loop = false;
                    System.out.println("Response null");
                } else {
                    try {
                        response = new Response(stringResponse);
                        System.out.println(response);
                        stringInterval = response.get("interval");
                        if (stringInterval != null) {
                            interval = Integer.parseInt(stringInterval);
                        } else {
                            interval = 0;
                        }
                        System.out.println(response.get("peers"));
                        Thread.sleep(interval);
                    } catch (Exception ex) {
                        Logger.getLogger(TrackerHandler.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
            System.out.println(stringResponse);
        }
        System.out.println("stop.");
    }
}
